package com.platform.modules.wallet.service.impl;

import cn.hutool.core.date.DateUtil;
import com.platform.common.web.service.impl.BaseServiceImpl;
import com.platform.modules.wallet.dao.WalletCashDao;
import com.platform.modules.wallet.domain.WalletAccount;
import com.platform.modules.wallet.domain.WalletCash;
import com.platform.modules.wallet.enums.AccountTypeEnum;
import com.platform.modules.wallet.enums.CashStatusEnum;
import com.platform.modules.wallet.service.WalletAccountService;
import com.platform.modules.wallet.service.WalletCashService;
import com.platform.modules.wallet.service.WalletService;
import com.platform.modules.wallet.vo.AccountVo01;
import com.platform.modules.wallet.vo.CashVo01;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Slf4j
@Service("walletCashService")
public class WalletCashServiceImpl extends BaseServiceImpl<WalletCash> implements WalletCashService {

    @Resource
    private WalletService walletService;
    @Resource
    private WalletAccountService walletAccountService;

    @Resource
    private WalletCashDao walletCashDao;

    @Autowired
    public void setBaseDao() {
        super.setBaseDao(walletCashDao);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean createCash(CashVo01 cashVo) {

        WalletCash cash = this.create(cashVo);

        AccountVo01 accountVo = new AccountVo01();
        accountVo.setOtherId(cash.getId());
        accountVo.setAmount(cashVo.getAmount());
        accountVo.setType(AccountTypeEnum.CASH);
        accountVo.setUserId(cashVo.getUserId());

        WalletAccount account = walletAccountService.createRecord(accountVo, WalletAccountService.NEGATIVE);

        walletAccountService.successRecord(account.getId());//完成账本记录
        walletService.subtract(accountVo.getAmount(), account.getUserId());//减掉余额

        return true;
    }

    private WalletCash create(CashVo01 vo) {
        WalletCash bean = getBean();
        bean.setAmount(vo.getAmount());
        bean.setUserId(vo.getUserId());
        this.add(bean);
        return bean;
    }

    private WalletCash getBean() {
        WalletCash cash = new WalletCash();
        cash.setCashStatus(CashStatusEnum.INIT.getCode());
        cash.setCreateTime(DateUtil.date());
        return cash;
    }

}
